package com.bhs.sansonglogistics.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.bhs.sansonglogistics.BuildConfig;
import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.MyApplication;
import com.bhs.sansonglogistics.bean.LoginBean;
import com.bhs.sansonglogistics.bean.MobileBean;
import com.bhs.sansonglogistics.dialog.PrivacyAgreementDialog;
import com.bhs.sansonglogistics.net.Config;
import com.bhs.sansonglogistics.net.NetApi;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.net.RetrofitUtils;
import com.bhs.sansonglogistics.ui.login.PhoneNumberLoginActivity;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.AuthUIControlClickListener;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.PreLoginResultListener;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OneClickLoginUtils implements NetCallBack, XPopupCallback {
    private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
    private Activity activity;
    private TokenResultListener mTokenResultListener;
    public NetApi netApi;
    String TAG = "hello";

    @SuppressLint("UseCompatLoadingForDrawables")
    public OneClickLoginUtils(Activity activity) {
        netApi = RetrofitUtils.getInstance().getRetrofit().create(NetApi.class);
        this.activity = activity;
        sdkInit(BuildConfig.AUTH_SECRET);
        //3.1、加速拉起一键登录页面
       //在不是一进app就需要登录的场景 建议调用此接口 加速拉起一键登录页面
       //等到用户点击登录的时候 授权页可以秒拉
       //预取号的成功与否不影响一键登录功能，所以不需要等待预取号的返回。
        mPhoneNumberAuthHelper.accelerateLoginPage(3000, new PreLoginResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                Log.e(TAG, "预取号成功: " + s);
            }

            @Override
            public void onTokenFailed(String s, String s1) {

            }
        });

        mPhoneNumberAuthHelper.setUIClickListener(new AuthUIControlClickListener() {
            @Override
            public void onClick(String code, Context context, String jsonString) {
                JSONObject jsonObj = null;
                try {
                    if (!TextUtils.isEmpty(jsonString)) {
                        jsonObj = new JSONObject(jsonString);
                    }
                } catch (JSONException e) {
                    jsonObj = new JSONObject();
                }
                switch (code) {
                    //点击授权页默认样式的返回按钮
                    case ResultCode.CODE_ERROR_USER_CANCEL:
                        Log.e(TAG, "点击了授权页默认返回按钮");
                        mPhoneNumberAuthHelper.quitLoginPage();
                        activity.finish();
                        break;
                    //点击授权页默认样式的切换其他登录方式 会关闭授权页
                    //如果不希望关闭授权页那就setSwitchAccHidden(true)隐藏默认的  通过自定义view添加自己的
                    case ResultCode.CODE_ERROR_USER_SWITCH:
                        activity.startActivity(new Intent(activity, PhoneNumberLoginActivity.class));
                        mPhoneNumberAuthHelper.quitLoginPage();
                        activity.finish();
                        break;
                    //点击一键登录按钮会发出此回调
                    //当协议栏没有勾选时 点击按钮会有默认toast 如果不需要或者希望自定义内容 setLogBtnToastHidden(true)隐藏默认Toast
                    //通过此回调自己设置toast
                    case ResultCode.CODE_ERROR_USER_LOGIN_BTN:
                        if (!jsonObj.optBoolean("isChecked")) {

                        }
                        break;
                    //checkbox状态改变触发此回调
                    case ResultCode.CODE_ERROR_USER_CHECKBOX:
                        Log.e(TAG, "checkbox状态变为" + jsonObj.optBoolean("isChecked"));
                        break;
                    //点击协议栏触发此回调
                    case ResultCode.CODE_ERROR_USER_PROTOCOL_CONTROL:
                        Log.e(TAG, "点击协议，" + "name: " + jsonObj.optString("name") + ", url: " + jsonObj.optString("url"));
                        break;
//                    //用户调用userControlAuthPageCancel后左上角返回按钮及物理返回键交由sdk接入方控制
//                    case ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYBTN:
//                        Log.e(TAG, "用户调用userControlAuthPageCancel后使用左上角返回按钮返回交由sdk接入方控制");
//                        mPhoneNumberAuthHelper.quitLoginPage();
//                        activity.finish();
//                        break;
//                    //用户调用userControlAuthPageCancel后物理返回键交由sdk接入方控制
//                    case ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYKEY:
//                        Log.e(TAG, "用户调用userControlAuthPageCancel后使用物理返回键返回交由sdk接入方控制");
//                        mPhoneNumberAuthHelper.quitLoginPage();
//                        activity.finish();
//                        break;

                    default:
                        break;

                }

            }
        });

        mPhoneNumberAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setAppPrivacyOne("《用户协议》", Config.getUserProtocolUrl())
                .setAppPrivacyTwo("《隐私协议》", Config.getPrivacyPolicyUrl())
                .setPrivacyEnd("并授权伞送得本机号码")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setAppPrivacyColor(Color.parseColor("#909399"), Color.parseColor("#000000"))

                .setLightColor(true)
                .setLogoImgDrawable(activity.getDrawable(R.mipmap.ic_sansong))
                .setLogoWidth(200)
                .setLogoHeight(100)
                .setNumberSizeDp(30)
                .setNumberSizeDp(30)
                .setSloganTextColor(Color.parseColor("#909399"))
                .setSloganTextSizeDp(13)
                .setSloganText(" ")
                .setLogBtnBackgroundDrawable(activity.getDrawable(R.drawable.bg_blue_8))
                .setLogBtnHeight(60)
                .setLogBtnTextSizeDp(18)
                .setSwitchAccText("切换手机号")
                .setSwitchAccTextSizeDp(18)
                .setNavHidden(true)
                .create());
    }

    public void sdkInit(String secretInfo) {
        mTokenResultListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {

                TokenRet tokenRet = null;
                try {
                    tokenRet = TokenRet.fromJson(s);
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.i("hello", "唤起授权页成功：" + s);
                        activity.finish();
                    }

                    if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.i("hello", "获取token成功：" + s);
                        getResultWithToken(tokenRet.getToken());
                        mPhoneNumberAuthHelper.setAuthListener(null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTokenFailed(String s) {
                Log.e("hello", "获取token失败：" + s);
                mPhoneNumberAuthHelper.hideLoginLoading();
                activity.startActivity(new Intent(activity, PhoneNumberLoginActivity.class));
                activity.finish();
                mPhoneNumberAuthHelper.quitLoginPage();
                mPhoneNumberAuthHelper.setAuthListener(null);
            }
        };
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(activity, mTokenResultListener);
//        mPhoneNumberAuthHelper.getReporter().setLoggerEnable(true);
        mPhoneNumberAuthHelper.setAuthSDKInfo(secretInfo);
    }

    public void pullPage(){
        mPhoneNumberAuthHelper.getLoginToken(activity, 3000);
    }

    private void getResultWithToken(String token) {
        networkRequestCode(netApi.getMobile(token, "logistics"), this, 0);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            MobileBean mobileBean = new Gson().fromJson(json, MobileBean.class);
            if (mobileBean.isStatus()) {
                login(mobileBean.getData().getMobile());
            } else {
                mPhoneNumberAuthHelper.hideLoginLoading();
                activity.startActivity(new Intent(activity, PhoneNumberLoginActivity.class));
                activity.finish();
                ToastUtil.show(mobileBean.getMsg());
            }
        } else {
            LoginBean loginBean = new Gson().fromJson(json, LoginBean.class);
            mPhoneNumberAuthHelper.hideLoginLoading();
            mPhoneNumberAuthHelper.quitLoginPage();
            if (!loginBean.isStatus()) {
                activity.startActivity(new Intent(activity, PhoneNumberLoginActivity.class));
                activity.finish();
            }
            MyUtils.login(activity, loginBean);
        }
    }

    private void login(String mobile) {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("login_type", "1");
        parameters.put("mobile", mobile);
        parameters.put("platform", "logistics");
        networkRequestCode(netApi.login(parameters), this, 110);
    }

    @Override
    public void onFailure(int requestCode) {
        mPhoneNumberAuthHelper.hideLoginLoading();
        mPhoneNumberAuthHelper.quitLoginPage();
    }

    @Override
    public void onCreated(BasePopupView popupView) {

    }

    @Override
    public void beforeShow(BasePopupView popupView) {

    }

    @Override
    public void onShow(BasePopupView popupView) {

    }

    @Override
    public void onDismiss(BasePopupView popupView) {

    }

    @Override
    public void beforeDismiss(BasePopupView popupView) {

    }

    @Override
    public boolean onBackPressed(BasePopupView popupView) {
        return false;
    }

    @Override
    public void onKeyBoardStateChanged(BasePopupView popupView, int height) {

    }

    @Override
    public void onDrag(BasePopupView popupView, int value, float percent, boolean upOrLeft) {

    }

    @Override
    public void onClickOutside(BasePopupView popupView) {

    }

    public int getValue(int dp) {
        /*获取dp值*/
        float pxValue2 = activity.getResources().getDimension(dp);//获取对应资源文件下的dp值
        return MyUtils.dip2px(activity, pxValue2);//将px值转换成dp值
    }

    private void networkRequestCode(Call<ResponseBody> dataCall, NetCallBack callBack, int requestCode) {
        //异步请求
        dataCall.enqueue(new Callback<ResponseBody>() {
            //请求成功回调
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 200) {
                    try {
                        String body = response.body().string();
                        JSONObject jsonObject = new JSONObject(body);
                        callBack.onResponse(requestCode, body, response);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    callBack.onFailure(requestCode);
                    ToastUtil.show("网络错误" + response.message() + response.code());
                }

            }

            //请求失败回调
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callBack.onFailure(requestCode);
                ToastUtil.show("网络错误" + t.toString());
            }
        });
    }
}
